import { electronIpcAdapter } from "@/api/adapter/ElectronAdapter";
import MessageUtil from "@/utils/model/MessageUtil";
import { RequireAdapter } from "@/api/types";

const adapter: RequireAdapter<any> = electronIpcAdapter;
// switch (Constant.mode) {
//   case PluginModeEnum.ELECTRON:
//     adapter = electronIpcAdapter;
//     break;
//   case PluginModeEnum.SERVER:
//     adapter = serverAdapter;
//     break;
//   default:
//     // 默认适配器
//     adapter = WebAdapter;
// }

/**
 * 请求后端
 *
 * @param url 请求的URL
 * @param body 请求的参数
 */
export async function useRequire<T>(url: string, body?: Record<string, any>): Promise<T> {
  try {
    const rsp = await adapter(url, body);
    const { code, msg, data } = rsp;
    if (code !== 200) {
      MessageUtil.error(msg);
      return Promise.reject(msg);
    }
    // 返回数据
    return data;
  } catch (e) {
    if (e instanceof Error) {
      MessageUtil.error(e.message);
    }
    // if (e.response) {
    //   return e?.response?.data as T;
    // }
    return Promise.reject(e);
  }
}
